const { formatDataType } = require('./tools/dataType');
const generateFile = require('../utils/generateFile ');

const renderEntityFile = (conf) => {
    console.log('--cur render entity --');
    return new Promise(async (resolve, reject) => {
        const tempFileContent = `${createDefineContentTemp(conf)}\n\n${createExportContentTemp(conf)}`;
        const { code } = await generateFile(`dist/entity/${conf.tbName}.js`, tempFileContent);
        if(code === 1) resolve({ code: 1, data: 'render entity.js successfully !'})
        else reject({ code : -1, data: 'render entity.js error !'});
    })
}

const createDefineContentTemp = ({tbName, tbEntity}) => {
    if(!tbName || !tbEntity) return new Error('no tbEntity input createContentTemp error !') ;
    let defineCont = `const Sequelize = require('sequelize')
    const conn = require('../orm/conn').connection();
    
    let ${tbName} = conn.define('${tbName}',{
            ${createTbEntityTemp(tbEntity)}
        }
    );`
    return defineCont;
}

const createTbEntityTemp = (tbEntity) => {
    // id: { type: Sequelize.INTEGER(11), allowNull: true, primaryKey: true, defaultValue: 0 },
    if(!Array.isArray(tbEntity)) return new Error('input tbEntity must be Array !');
    let strArr = [];
    for (const item of tbEntity) {
        const { Field, Type, Null, Key, Default, Extra } = item;
        let incrstr = ''
        if(Extra === 'auto_increment') incrstr = ', autoIncrement: true';
        let str = `${Field}: { type: Sequelize.${formatDataType(Type)}, allowNull: ${Null === 'YES' ? true : false}, primaryKey: ${Key === 'PRI' ? true : false}, defaultValue: ${Default}, Extra: '${Extra}' ${incrstr} }`
        strArr.push(str);
    }
    return strArr.join(',\n').toString();
}

const createExportContentTemp = ({tbName, tbEntity}) => {
    if(!tbName || !tbEntity) return new Error('no tbEntity input createContentTemp error !') ;
    let exportCont = `module.exports = {
        ${tbName},
        // findAndCountAll
        async findAndCountAll(req,res){
            const { body: { limit, offset }} = req;
            let pageobj = undefined;
            if(limit && offset) pageobj = { limit: Number(limit), offset: Number(offset) };
            const data = await ${tbName}.findAndCountAll(pageobj);
            res.send(data);
        },
        // findById
        async findById(req,res){
            const { body: { id } } = req;
            const data = await ${tbName}.findById(id);
            res.send(data);
        },  
        // create
        async create(req,res){
            const { body } = req;
            const data = await ${tbName}.create(body);
            res.send(data);
        },
        // deleteById
        async deleteById(req,res){
            const { body: { id } } = req;
            const data = await ${tbName}.destroy( { where:{ id } });
            res.send({deleteRows: data});
        },
        // updateById
        async updateById(req,res){
            const { body, body: { id } } = req;
            const data = await ${tbName}.update( body, {  where: { id } });
            res.send({effectRows: data});
        }
    };`
    return exportCont;
}

module.exports = renderEntityFile